<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        
    </style>
</head>
<body>
    <h2>这是登录页面</h2>
    用户名：<input type="text" id="username"><br>
    密码：<input type="text" id="password"><br>
    <input type="button" value="登录" id="btn"><br>
    <a href="./index.html">回首页</a><br>
    <a href="./register.html">去注册</a><br>
</body>
<script src="./js/ajax.js"></script>
<script src="./js/Toast.js"></script>
<script>
    
    const un = document.getElementById("username")
    const pw = document.getElementById("password")
    const btn = document.getElementById("btn")

    btn.onclick = function(){
        ajax({
            data:{
                username: un.value,
                password: pw.value
            },
            url:"http://localhost:3000/login",
            success(res){
                res = JSON.parse(res);
                if(res.code === 0){
                    new Toast({
                        text:"该用户未注册，请先注册",
                        color: "red",
                        position: "center",
                        callback:()=>{
                            location.assign("./register.html#"+un.value);
                        }
                    });
                }else if(res.code === 1){
                    sessionStorage.setItem("token", res.token);
                    new Toast({
                        text:"登录成功",
                        color: "green",
                        position: "top",
                        callback:()=>{
                            location.assign("./index.html");
                        }
                    });
                }else if(res.code === 2){
                    new Toast({
                        text:"密码不对，请重新输入",
                        color: "red",
                        position: "center",
                        callback:()=>{
                            pw.value = "";
                            pw.focus();
                        }
                    });
                }
            }
        })
    }

</script>
</html>